<!-- 当前所有直播列表（在线的，近一周的）,所有角色可见，但开直播只有老师可开 -->
<template>
    <div class="container table-page">
        <div class="table-search-box" @keyup.enter="search()">
            <div class="search-item">
                <label>直播名称：</label>
                <div class="table-query-input">
                    <el-input v-model="queryData.title" clearable placeholder="名称">
                    </el-input>
                </div>
            </div>
            <div class="search-item">
                <label>创建人：</label>
                <div class="table-query-input">
                    <el-input v-model="queryData.anchor" clearable placeholder="创建人">
                    </el-input>
                </div>
            </div>
            <div class="search-item">
                <label>起止时间：</label>
                <div class="table-query-input">
                    <el-date-picker v-model="queryData.dateRange" type="datetimerange" range-separator="-"
                        start-placeholder="开始日期" end-placeholder="结束日期" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
            </div>
            <div class="search-item">
                <label>创建时间：</label>
                <div class="table-query-input">
                    <el-date-picker v-model="queryData.createTimeRange" type="datetimerange" range-separator="-"
                        start-placeholder="日期" end-placeholder="日期" value-format="yyyy-MM-dd HH:mm:ss">
                    </el-date-picker>
                </div>
            </div>
            <div class="search-item">
                <el-button type="primary" icon="el-icon-search" :loading="tableLoading" @click="search()">搜索
                </el-button>
            </div>
            <div class="search-item">
                <el-button icon="el-icon-refresh" :loading="tableLoading" @click="resetSearch()">重置
                </el-button>
            </div>
        </div>
        <div class="table-operation-box">
            <el-button v-if="role === '老师'" type="primary" plain style="margin-bottom: 2em" icon="el-icon-plus"
                @click="createRoom">创建直播间
            </el-button>
        </div>
        <div class="table-data-box">
            <el-table ref="table" border v-loading="tableLoading" :highlight-current-row="true" :data="tableData"
                style="width: 100%">
                <el-table-column type="index">
                </el-table-column>
                <el-table-column prop="title" label="直播标题" width="180" align="center"></el-table-column>
                <el-table-column prop="startedAt" label="开始时间" width="180" align="center"></el-table-column>
                <el-table-column prop="stoppedAt" label="结束时间" width="180" align="center"></el-table-column>
                <el-table-column prop="status" label="状态" width="180" align="center">
                    <template slot-scope="scope">
                        {{ scope.row.status | statusMap }}
                    </template>
                </el-table-column>
                <el-table-column prop="anchorNick" label="创建人" width="180" align="center"></el-table-column>
                <!-- <el-table-column prop="anchorId" label="创建人id" width="180" align="center"></el-table-column> -->
                <el-table-column prop="createdAt" label="创建时间" width="180" align="center"></el-table-column>
                <el-table-column label="操作" width="180">
                    <template slot-scope="scope">
                        <el-button v-if="scope.row.status == 0" size="mini" type="primary"
                            @click="handleStart(scope.$index, scope.row)">开直播</el-button>
                        <!-- <el-button size="mini" @click="handleEdit(scope.$index, scope.row)">编辑</el-button> -->
                        <el-button size="mini" type="danger" @click="handleDelete(scope.$index, scope.row)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>

        </div>
        <div v-if="pageData.total > 0" class="xy-between table-page-box">
            <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" background :current-page.sync="pageData.currentPage" :page-sizes="pageData.pageSizes"
                :page-size.sync="pageData.pageSize" layout="total,  prev, pager, next, sizes, jumper"
                :total="pageData.total">
            </el-pagination>
        </div>
    </div>
</template>
<script>
import service, { get ,post} from '@/api/request'
import {pageEvents} from '@/layout/mixin/iVue.js'
export default {
    mixins:[pageEvents],
    data() {
        return {
            // fieldsMap:Object.freeze({

            // }),
            role: '老师',
            originQueryData: JSON.stringify({
                title: '',
                anchor: '',
                dateRange: [],
                createTimeRange:[]
            }),
            tableLoading: false,

            queryData: {
                title: '',
                anchor: '',
                dateRange: [],
                createTimeRange:[]
            },
            tableData: [
            ],
            pageData: {
                currentPage: 1,
                pageSize: 10,
                total: 0,
                pageSizes: Object.freeze([10, 20, 30, 40])
            },
            live_jump_url: '',
            proxyAddr: '/code',
            token: 'eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJ1c2VybmFtZSI6ImFkbWluIiwic3ViIjoiMSIsImlhdCI6MTczNDU5MDcxNSwiZXhwIjoxNzM1MTk1NTE1fQ.WiWYwPUvV9mmIYjoZlrAyxe9gtXJVcvdJbjOKeV_z5w'
        }
    },
    created() {
        // service({
        //     url: '/live/roomInfos',
        // }).then(res => {
        //     this.tableData = res
        //     console.log(this.tableData)
        // })
        this.resetSearch()
    },
    filters: {
        statusMap(key) {

            const map = {
                0: '准备中', 1: '已开始', 2: '已结束'
            }
            return map[key]
        }
    },
    methods: {
        parseToken(token) {
            var strings = token.split(".");
            var userinfo = JSON.parse(decodeURIComponent(escape(window.atob(strings[1].replace(/-/g, "+").replace(/_/g, "/")))));
            return userinfo
        },
        createRoom() {
            const now = new Date()
            service.post(`${this.proxyAddr}/api/v2/live/create`, {
                // createNewImMessageGroup的创建者id
                anchor: '1',
                anchor_nick: '骆老师',
                extends: JSON.stringify({
                    userNick: '骆老师',
                    userAvatar: '',
                }),
                mode: 0, // 直播间类型，0：普通直播，1：连麦直播--竖屏不提供连麦功能
                notice: '直播公告',
                title: `直播测试${now.getMonth() + 1}${now.getDate()}`,
                // 新版 v2 接口使用，请结合实例情况是否开启
                im_server: ['aliyun_new'],
            },
                {
                    headers: {
                        Authorization: `Bearer ${this.token}`,
                        accept: 'application/json',
                        'Content-Type': 'application/json',
                    },
                }).then(res => {
                    this.search()
                    // 直播间已开启，直播间id:xxxx,是否现在直播
                    console.log(this.parseToken(this.token))
                    const confirm = true;
                    if (confirm == true) {
                        service.post(
                            `${this.proxyAddr}/api/v1/live/getLiveJumpUrlInBrowse`,
                            {
                                live_id: res.id,
                                user_id: '1',
                                user_name: this.parseToken(this.token).username,
                                version: 'v2',
                            },
                            {
                                headers: {
                                    Authorization: `Bearer ${this.token}`,
                                    accept: 'application/json',
                                    'Content-Type': 'application/json',
                                },
                            }
                        ).then(res1 => {
                            this.live_jump_url = res1.live_jump_url;
                            window.location.href = this.live_jump_url;

                        });
                    }
                })
        },
        handleStart(index, row) {
            // const userId = "me"
            const userId = undefined
            if (row.anchor === userId) {
                // 生成推流地址开播
                service.post(
                    `${this.proxyAddr}/api/v1/live/getLiveJumpUrlInBrowse`,
                    {
                        live_id: row.id,
                        user_id: row.anchorId,
                        user_name: this.parseToken(this.token).username,
                        version: 'v2',
                    },
                    {
                        headers: {
                            Authorization: `Bearer ${this.token}`,
                            accept: 'application/json',
                            'Content-Type': 'application/json',
                        },
                    }
                ).then(res => {
                    window.location.href = (res.live_jump_url)
                });
            } else {
                this.$message.error('只有主播才能开直播');
            }
        },
        // handleEdit(index, row) {
        //     console.log('编辑', index, row);
        // },
        handleDelete(index, row) {
            // 开始中不可删除
            if(row.status==1){
                return this.$message('开始中的直播间不可删除');
            }
            // console.log('删除', index, row);
            // this.liveList.splice(index, 1);
            this.$confirm("确认删除?此操作数据不可回复", "警告", {
                type:'warning',
                callback:(action,instance)=>{
                    if(action=='confirm'){
                        service.delete('/live/roomInfos/batchDelete',{
                            data:[row.id]
                        }).then(res=>{
                            this.search()
                        })
                    }
                }
            })
        },
        resetSearch() {
            this.pageData.currentPage = 1
            this.queryData = JSON.parse(this.originQueryData)
            this.search();
        },
        async search() {
            const res = await this.loadTable("/live/roomInfos", this.queryData);

        },
        loadTable(
            url,
            queryData,
            setResult = true,
            map,
            errorMessage = {
                message: "数据加载失败"
            }
        ) {
            if (this.tableLoading) {
                return Promise.resolve();
            }
            this.tableLoading = true;
            return post(
                url,
                {
                    current: this.pageData.currentPage,
                    size: this.pageData.pageSize,
                    pageSize: this.pageData.pageSize,
                    pageCurrent: this.pageData.currentPage,
                    ...this.queryData,
                },
                errorMessage
            )
                .then(async res => {
                    let list = res.records || res.result || res || [];

                    list.forEach(da => {
                        da.opLoading = false
                        da.edit = false
                        da.sortEdit = false
                        da.nameEdit = false
                    });

                    if (setResult) {
                        this.tableData = list;

                    }

             
                    this.pageData.total = res.total || 0;
                    this.pageData.currentPage =
                        res.current || 1;
                    this.pageData.pageSize = res.size || 10;
              

                    
                    if (this.pageData.currentPage > 1 && list.length === 0) {

                        
                        this.pageData.currentPage = 1
                        // const res1 = await this.loadTable(url, queryData, false)
                        const res1 = await this.loadTable(url, queryData)
                        return res1;
                    }
                    return res;
                })
                .finally(() => {
                    this.tableLoading = false;
                });
        },
       
    }
}
</script>


<style>
.container {
    /* width: 1238px; */
    margin-left: 15px;
    margin-right: 15px;
    width: 1208px;
    box-sizing: border-box;
    padding: 15px;
    /* height: 610.8px; */
    outline: #f00 solid 1px;
}
</style>